"use strict"

const h = require('./fetch/yy')
const f = require('./collect')
const mysql = require('mysql2/promise')
const config = require('./config')
const insert_cate = require('./insert_cate')

h.run()
    .then(data => {
        let connect = null
        const gen_query = sql => () => connect.query(sql)

        const ids = `("${f.pluck(data, 'id').join('","')}")`

        const needle_sql = `SELECT id,name,url,room_name FROM ${config.table} WHERE id IN ${ids} AND ${config.off_line}`

        const delete_sql = `DELETE FROM ${config.table} WHERE id IN ${ids}`

        const update_sql = `UPDATE ${config.table} SET ${config.off_line}`

        const insert_sql = `INSERT INTO ${config.table} (${config.cols.join(',')},status) VALUES ${
            data.map(row => `(${config.cols.map(col => `'${row[col]}'`).join(',')},1)`).join(',')
        }`
        
        mysql.createConnection(config.DB)
            .then(c => connect = c)
            //不用每次都更新所有平台的栏目分类
            .then(c => insert_cate(data, c))
            .then(gen_query(needle_sql))
            .then(gen_query(delete_sql))
            .then(gen_query(update_sql))
            .then(gen_query(insert_sql))
            .then(_=> connect.end())
            .catch(sql_error => {
                connect.end()
                console.error(sql_error)
            })
    })
    .catch(console.error)

// fetch("http://apibj.fanxing.kugou.com/VServices/IndexService.IndexService.getLiveRoomListByType/1")
//     .then(_=>_.text())
//     .then( _=>_.slice(_.indexOf('{'), _.lastIndexOf('}')+1) )
//     .then(console.log)

